package cn.keniykey.mc.landterritory.land;

import java.sql.ResultSet;
import java.util.UUID;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;

import cn.keniykey.mc.landterritory.LandTerritoryMain;
import cn.keniykey.mc.landterritory.config.ConfigurationManager;
import cn.keniykey.mc.landterritory.config.LanguageManager;
import cn.keniykey.mc.landterritory.database.DataBaseManager;
import cn.keniykey.mc.landterritory.event.PlayerEnterLeaveLandEvent;
import cn.keniykey.mc.landterritory.land.api.Land;

public final class PlayerJoinQuitListener implements Listener{
	
	@EventHandler(priority = EventPriority.MONITOR)
	public void onPlayerJoin(final PlayerJoinEvent e) {
		final Player player = e.getPlayer();
		if(!player.isOnline()) return;
		final UUID player_uuid = player.getUniqueId();
		Bukkit.getScheduler().runTaskAsynchronously(LandTerritoryMain.getPlugin(), ()->{
			try(final ResultSet rs_player = DataBaseManager.getDataBaseCore().getPlayer(player_uuid)) {
				if(rs_player.next()) {
					LandManager.getLandManager().hashmap_players_maxlimit.put(player_uuid, rs_player.getInt("amount"));
					return;
				}
			}catch(Exception ex) {
				ex.printStackTrace();
				player.sendMessage(LanguageManager.getChatPrefix() + LanguageManager.getLang(1001000) + "DataBaseCore.getPlayer(uuid)");
				return;
			}
			try {
				final int amount = Math.max(0, ConfigurationManager.View_LandMain_LandLimit_NewPlayer);
				DataBaseManager.getDataBaseCore().initPlayer(player_uuid, amount);
				LandManager.getLandManager().hashmap_players_maxlimit.put(player_uuid, amount);
			}catch(Exception ex) {
				ex.printStackTrace();
				player.sendMessage(LanguageManager.getChatPrefix() + LanguageManager.getLang(1001000) + "DataBaseCore.initPlayer(uuid, " +
				ConfigurationManager.View_LandMain_LandLimit_NewPlayer + ")");
			}
		});
	}
	@EventHandler(priority = EventPriority.LOWEST)
	public void onPlayerQuit(final PlayerQuitEvent e) {
		final Player player = e.getPlayer();
		final UUID player_uuid = player.getUniqueId();
		LandTransferUtil.hashmap_transfer_countdown.remove(player_uuid);
		
		LandManager.getLandManager().hashmap_players_maxlimit.remove(player_uuid);
		final Land land = LandManager.getLandManager().getCircleDetectionLand(player);
		if(land == null) return;
		LandManager.getLandManager().conmap_players_in.remove(player_uuid);
		Bukkit.getScheduler().runTaskAsynchronously(LandTerritoryMain.getPlugin(), ()->{
			Bukkit.getPluginManager().callEvent(new PlayerEnterLeaveLandEvent(player, null, land));
		});
	}
}